package zsc.liangyi.blog.web.client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import zsc.liangyi.blog.model.ResponseData.ResponseData;
import zsc.liangyi.blog.model.domain.User;
import zsc.liangyi.blog.service.UserService;

import java.util.Date;

@Controller
@Slf4j
public class RegisterController {
    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String register(){
        return "comm/register";
    }

    @PostMapping("/register")
    @ResponseBody
    public ResponseData register(@RequestParam String username,
                                 @RequestParam String password,
                                 @RequestParam String repassword,
                                 @RequestParam String email){
        //服务器端验证注册信息
        if(!password.equals(repassword)){
            return ResponseData.fail("密码不一致");
        }
        if(userService.getByUserName(username)!=null){
            return ResponseData.fail("用户名已被注册");
        }
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        //创建User
        User user=new User();
        user.setCreated(new Date());
        user.setUsername(username);
        user.setPassword(encoder.encode(password));
        user.setEmail(email);
        user.setValid(1);
        if(userService.addUser(user)>0){
            //默认分配为普通用户，可由admin更改
            userService.addAuthorityByUser(user.getId(),2);
            return ResponseData.success("注册成功");
        }else{
            return ResponseData.fail();
        }

    }

}
